<!-- eslint-disable vue/multi-word-component-names -->
<!-- 宠物详情页面 -->
<template>
  <div class="pet-detail-container">
    <div class="pet-image-info-container">
      <!-- 图片 -->
      <div class="pet-image">
        <img 
          :src=" picData[0]" 
          alt="宠物图片" 
          class="pet-pic"
        />
      </div>
      <!-- 宠物信息 -->
      <div class="pet-info">
        <div class="pet-name">宠物名字：{{ petDetailData.petName }}</div>

        <div class="pet-deposit">押金：{{ petDetailData.deposit }}</div>

        <div class="pet-breed">品种：{{ petDetailData.breed }}</div>
        <div class="pet-gender">性别：{{ petDetailData.gender }}</div>
        <div class="pet-age">年龄：{{ petDetailData.age }}</div>
        <div class="pet-region">地区：{{ petDetailData.region }}</div>

        <div class="pet-vaccinated">疫苗情况：{{ petDetailData.vaccinated === "1" ? "已接种" : "未接种" }}</div>
        <div class="pet-healthy">健康状态：{{ petDetailData.healthy === "1" ? "健康" : "患病" }}</div>
        <div class="pet-adopted">是否被领养：{{ petDetailData.adopted === "1" ? "已领养" : "未领养" }}</div>
        <div class="pet-office">来源：{{ petDetailData.office === "1" ? "平台发布" : "个人发布" }}</div>

        <el-button @click="dialogFormVisible = true; AdoptBtn()" class="btn">领养</el-button>
        <!-- <button  class="btn" >领养</button> -->
      </div>
    </div>
    <div class="title">描述</div>
    <!-- 宠物描述 -->
    <div class="pet-describe">
      {{ petDetailData.details }}
    </div>
  </div>

  <!-- 表单：领养需要填写 -->
  <el-dialog v-model="dialogFormVisible" title="请填写领养信息" width="500">
    <!-- 填写领养信息 -->
    <el-form :model="form">
      <el-form-item label="领养原因" :label-width="formLabelWidth">
        <el-input v-model="form.reason" autocomplete="off" />
      </el-form-item>
      <el-form-item label="领养人地址（收货地址）" :label-width="formLabelWidth">
        <el-input v-model="form.adopterAddress" autocomplete="off" />
      </el-form-item>
      <el-form-item label="上传证明图片" :label-width="formLabelWidth">
        <div class="upload-container">
          <el-upload
            class="upload-demo"
            ref="uploadRef"
            action="#"
            drag
            :on-change="handlePictureChange"
            :show-file-list="false"
            :auto-upload="false"
          >
            <div class="el-upload__text">
              拖拽文件，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              请上传能证明您有能力领养宠物的图片
            </div>
          </el-upload>
          <div v-if="previewUrl" class="preview-container">
            <img :src="previewUrl" class="preview-image" alt="预览图" />
            <el-button @click="removeImage" type="danger" size="small">删除图片</el-button>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <!-- 只读功能 -->
    <!-- <el-form-item label="宠物ID" :label-width="formLabelWidth">
      <el-input v-model="form.petId" disabled placeholder="系统自动填充" />
    </el-form-item>
    <el-form-item label="领养人ID" :label-width="formLabelWidth">
      <el-input v-model="form.adopterId" disabled placeholder="系统自动填充" />
    </el-form-item> -->
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false; resetUpload">取消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false; confrimAdopt()">确认领养</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
import { getPetDetailAPI,postImageAPI,postPetAdoptApplicationAPI } from "@/api/pet";
import { onMounted, ref, reactive } from "vue";
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const route = useRoute();

// 当前渲染的宠物的id
const pet_id = Number(route.params.id);
// console.log("当前宠物的id", pet_id);

const UserStore = useUserStore()
const userID = UserStore.user.user_id
// console.log("当前用户ID：",userID)

// 存储宠物图片
const picData=ref([])

// 存储宠物详细信息
const petDetailData = ref([]);
const getPetDetail = async () => {
  const res = await getPetDetailAPI(pet_id);
  petDetailData.value = res;

  picData.value=petDetailData.value.imageUrls

  // console.log(picData.value)
  // console.log(petDetailData.value);
};
onMounted(() => {
  getPetDetail();
});

// 表单数据存储
const form = reactive({
  reason: "",//领养原因
  adopterAddress: "",//领养人地址（收货地址）
  petId: pet_id,//领养宠物的ID（当前宠物的ID）
  adopterId: userID, //领养人的ID（当前用户的ID）
  images:[], //上传的图片
})

const formLabelWidth = '180px'//输入框标题宽度
const dialogFormVisible = ref(false)

// 上传图片相关
const uploadRef = ref(null)
const uploadFile = ref(null)// 存储上传的文件对象
const previewUrl=ref("")//存储上传图片的URL
// 处理图片上传
const handlePictureChange = async (file, fileList) => {
    const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
    const isLt50M = file.raw.size / 1024 / 1024 < 10

    if (!isJPG) {
        ElMessage.error('上传图片只能是 JPG/PNG 格式!')
        return false
    }
    if (!isLt50M) {
        ElMessage.error('上传图片大小不能超过 10MB!')
        return false
    }

    try {
        // 创建FormData对象，用于上传文件
        const formData = new FormData()
        formData.append('file', file.raw)

        // 调用上传图片的接口
        const res = await postImageAPI(formData)
        console.log(res.url)
        
        // 处理接口返回的数据，将url存储在ruleForm.imageUrls数组中
        form.images.push(res.url)

        previewUrl.value=res.url
        uploadFile.value = file.raw
    } catch (error) {
        ElMessage.error('图片上传失败')
    }
}
// 删除预览图片
const removeImage = () => {
  uploadFile.value = null;
  previewUrl.value = '';
  // 从数组中移除对应的图片URL
  const index =form.images.indexOf(previewUrl.value)
    if (index > -1) {
      form.images.splice(index, 1)
    }
}
// 领养按钮
const AdoptBtn = () => {
  console.log("点击领养按钮")
}

// 确认领养
const confrimAdopt=async()=>{
  console.log("点击确认领养按钮")
  console.log("表单数据:", form)
  
  // 申请领养接口
  const res=await postPetAdoptApplicationAPI(form)
  // console.log(res)

  if(res.success === true){
    ElMessage.success('申请领养成功，请等待审核')
  }else{
    ElMessage.error(res.success)
  }
}
</script>

<style scoped lang="scss">
.pet-detail-container {
  width: 1200px;
  height: 800px;
  margin-top: 100px;
  // border: 1px solid black;
  display: flex;
  flex-direction: column;

}

.pet-image-info-container {
  display: flex;
  width: 100%;
  height: 500px;
  padding: 10px;
}

.pet-image {
  width: 50%;
  margin: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  // border: 1px solid red; 
  overflow: hidden; /* 防止图片溢出容器 */
  position: relative; /* 确保绝对定位元素相对于此容器 */
}

.pet-pic {
  width: 100%;
  height: 100%; 
  object-fit: cover; /* 保持图片比例，覆盖整个容器 */
  object-position: center; /* 居中显示图片 */
}

.pet-info {
  width: 50%;
  margin: 10px;
  padding-left: 80px;
  position: relative;

  .pet-name {
    font-size: 30px;
    font-weight: bold;
    margin-bottom: 15px;
  }

  .pet-deposit {
    padding-bottom: 15px;
    font-size: 25px;
    font-weight: 550;
    margin-bottom: 20px;
    border-bottom: 1px solid rgb(202, 202, 188);
  }

  .pet-breed,
  .pet-gender,
  .pet-age,
  .pet-region {
    margin-bottom: 10px;
    font-size: 20px;
    font-weight: 550;
  }

  .pet-region {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid rgb(202, 202, 188);
  }

  .pet-vaccinated,
  .pet-healthy,
  .pet-adopted,
  .pet-office {
    margin-bottom: 10px;
    font-size: 20px;
    font-weight: 550;
  }

}

.title {
  margin-left: 20px;
  font-size: 20px;
}

.pet-describe {
  font-size: 15px;
  margin: 20px;
  padding: 15px;
  background: #f7f5f6;
}

.btn {
  position: absolute;
  bottom: 10px;
  right: 70px;
  background: #055B5C;
  width: 100px;
  height: 30px;
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.btn:hover {
  background: #087d7e;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  cursor: pointer;
}

.upload-container {
  .preview-container {
    margin-top: 10px;
  }
  
  .preview-image {
    max-width: 100%;
    max-height: 100px;
    border-radius: 4px;
    border: 1px solid #ebeef5;
  }
}
</style>